package service;

import mapper.HourseMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import pojo.House;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 业务层
 * 1. 相应HouseView的调用
 * 2. 完成对房屋信息的各种操作
 */

public class HouseService {
    String resource = "mybatis-config.xml";
    InputStream inputStream;

    {
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();

    //添加房屋
    public boolean add(House newHouse) throws IOException {

        boolean flag = false;
        SqlSession sqlSession = sqlSessionFactory.openSession();

        HourseMapper hourseMapper = sqlSession.getMapper(HourseMapper.class);
        flag = hourseMapper.addHouse(newHouse);

        sqlSession.commit();
        sqlSession.close();
        return flag;
    }
    //返回房屋列表
    public List<House> list(){
        List<House> HouseList= new ArrayList<>();
        SqlSession sqlSession = sqlSessionFactory.openSession();

        HourseMapper hourseMapper = sqlSession.getMapper(HourseMapper.class);
        HouseList = hourseMapper.SelectAll();
        sqlSession.close();
        return HouseList;
    }

    public House select(int sel ){
        SqlSession sqlSession = sqlSessionFactory.openSession();

        HourseMapper hourseMapper = sqlSession.getMapper(HourseMapper.class);
        House house = hourseMapper.SelectHouse(sel);
        System.out.println(house);
        sqlSession.close();
        return house;
    }
    //删除房屋
    public Boolean delete(int del){
        boolean flag;
        SqlSession sqlSession = sqlSessionFactory.openSession();

        HourseMapper hourseMapper = sqlSession.getMapper(HourseMapper.class);
        flag = hourseMapper.deleteHouse(del);
        sqlSession.commit();
        sqlSession.close();
        return flag;

    }
    //修改房源
    public Boolean revise(House newHouse) {
        boolean flag;
        HourseMapper hourseMapper = sqlSession.getMapper(HourseMapper.class);
        flag = hourseMapper.updateHouse(newHouse);
        //4. 释放资源
        sqlSession.commit();
        sqlSession.close();
        return flag;
    }




}
